package Map测试;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Copyright (C) 2023 思创数码科技股份有限公司
 * <p/>
 * 版权所有
 * <p/>
 * 类名　　  : HashThreadTest
 * 功能概要  :
 *
 * @author yangwk
 * @date 2024/8/27 16:38
 */
public class HashThreadTest {
    //创建一个hashMap类变量，指定数组空间为2
    static Map<Integer, Integer> map = new HashMap<Integer, Integer>(2);

    public static void main(String[] args) throws InterruptedException {
        final AtomicInteger at = new AtomicInteger(0);
        //控制并发原子操作final
        CountDownLatch countDownLatch = new CountDownLatch(4);
        //并发计数器
        for (int i = 0; i < 4; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (at.get() < 100000) {
                        //向map中添加元素
                        map.put(at.get(), at.get());
                        at.incrementAndGet();//对int加1
                    }
                    countDownLatch.countDown();
                }
            }).start();
//阻塞当前主线程，等待4个线程全部执行完毕
        }
        countDownLatch.await();
        Set<Integer> keySet = map.keySet();
        Iterator<Integer> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();

            System.out.println("key:" +next + "，value:" + next);
        }
    }
}
